package com.woniu.config;

import com.fasterxml.jackson.databind.ObjectMapper;


import com.woniu.util.ResponseResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class MyLogoutHandler implements LogoutSuccessHandler {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public void onLogoutSuccess (HttpServletRequest req, HttpServletResponse resp, Authentication authentication) throws IOException, ServletException {
        String token = req.getHeader("token");
        if(!StringUtils.isEmpty(token)){
            SecurityContextHolder.clearContext();
        }
        String username = req.getParameter("username");
        redisTemplate.delete(username);
        ResponseResult result = new ResponseResult(666,"欢迎"+username+"下次光临");
        resp.setContentType("application/json;charset=utf-8");
        try {
            resp.getWriter().write(new ObjectMapper().writeValueAsString(result));
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
